package com.hxkcloud.patient.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Message;
import android.provider.MediaStore;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.adapter.ImageAdapter;
import com.hxkcloud.patient.beans.DischargeSummaryBean;
import com.hxkcloud.patient.beans.FileUploadBean;
import com.hxkcloud.patient.beans.ImageBean;
import com.hxkcloud.patient.config.ApplicationConfig;
import com.hxkcloud.patient.photo.MeenoPhotoActivity;
import com.hxkcloud.patient.photo.UriUtils;
import com.hxkcloud.patient.popup.PictureSelectPopupWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.ImageVideoUtils;
import com.hxkcloud.patient.utils.MyImageCompresseUtils;
import com.hxkcloud.patient.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AskQuestionActivity extends BaseActivity implements View.OnClickListener,ImageAdapter.OnItemClickListener,PictureSelectPopupWindow.FinishListener {
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_collect;


    private LinearLayout ll_root_askQuestion;
    private TextView tv_send;
    //输入
    private EditText editText_ask;
    private TextView tv_nums;
    private CharSequence temp;
    private final int charMinNum = 10;
    private boolean edit_flag =false;
    //popwindow
    View askView;
    private TextView tv_quit_pop;
    private TextView tv_sure_pop;
    private PopupWindow askQuestPop;

    private RecyclerView recyclerView_image;
    List<ImageBean> imageBeanList;
    private ImageAdapter imageAdapter;
    private List<String> images;

    private PictureSelectPopupWindow picSelect;

    private DischargeSummaryBean dischargeSummaryBean;

    //退出pop
    private PopupWindow popup_easynotice1;
    private TextView tv_cancle;
    private TextView tv_sure;

    private int clickPosition = 0;




    private static final int TAKE_PHOTO_PICTURE = 1;
    private static final int SELECT_PICTURE = 3;
    private static final int CUT_PICTURE = 5;
    private static final int FINISH_CODE = 10;
    private static final int DELETE_CODE = 11;

    private List<FileUploadBean> fileResultBean;
    // 上传文件的内容

    private File cameraPath;
    private File cameraFile;
    private String cameraFileName;

    public static final int PHOTO_MANY = 1002;// 用户选择多图的req

    private Uri imageUri = null;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what){
            case MessageCode.NETWORKCODE_FILEUPLOAD_SUCCESS:
                if (msg.obj != null) {
                    fileResultBean = (List<FileUploadBean>) msg.obj;
                    //fileResultBean.get(0).getUrl();
                    if (fileResultBean == null || fileResultBean.size() == 0) {
                        toastMsg("图片上传失败!");
                        return;
                    }
                    for(int i = 0; i < fileResultBean.size() ; i++)
                    {
                        images.add(0, fileResultBean.get(i).getFilePath());
                        ImageBean imageBean = new ImageBean();
                        imageBean.setImageType(2);
                        imageBean.setImage(fileResultBean.get(i).getUrl());
                        imageBeanList.add(0, imageBean);
//                        Log.i("--imageBean-->",fileResultBean.get(i).getUrl());
                    }
//                    images.add(0, fileResultBean.get(0).getFilePath());
//                    ImageBean imageBean = new ImageBean();
//                    imageBean.setImageType(1);
//                    imageBean.setImage(cameraFile.getAbsolutePath());
//                    imageBeanList.add(0, imageBean);
                    if (imageBeanList.size() == 10) {
                        imageBeanList.remove(imageBeanList.size() - 1);
                    }
                    imageAdapter.notifyDataSetChanged();
                }
                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.fileuploadfail));
                }
                break;
            case MessageCode.NETWORKCODE_EDITUPUSERSANDDOCTOR_SUCCESS:
                setResult(2,new Intent());
                finish();
                break;
            case MessageCode.NETWORKCODE_EDITUPUSERSANDDOCTOR_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }else {
                    toastMsg("数据上传失败");
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ask_question);
        images = new ArrayList<>();
        imageBeanList = new ArrayList<>();
        initView();
        showAskPop();
        initData();
        initListener();

    }

    private void showAskPop() {

        askView = LayoutInflater.from(AskQuestionActivity.this).inflate(R.layout.popwinds_askquestionactivity,null);
        tv_quit_pop = (TextView) askView.findViewById(R.id.askquestion_quit);
        tv_sure_pop = (TextView) askView.findViewById(R.id.askquestion_sure);
        tv_quit_pop.setOnClickListener(this);
        tv_sure_pop.setOnClickListener(this);
        askQuestPop = new PopupWindow(askView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        askQuestPop.setFocusable(true);
        askQuestPop.setOutsideTouchable(true);
        askQuestPop.setTouchable(true);
        askQuestPop.setBackgroundDrawable(new BitmapDrawable());
    }


    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_collect = (TextView) findViewById(R.id.tv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText("提问");



        ll_root_askQuestion = (LinearLayout) findViewById(R.id.activity_ask_question);
        tv_send = (TextView) findViewById(R.id.ask_consult_ask);
        editText_ask = (EditText) findViewById(R.id.editText);
        tv_nums = (TextView) findViewById(R.id.textView3);
        recyclerView_image = (RecyclerView) findViewById(R.id.recyclerview_image);
        picSelect = new PictureSelectPopupWindow(this, screenWidth,screenHeight, this);

    }

    @Override
    protected void initListener() {

        iv_back.setOnClickListener(this);
        tv_send.setOnClickListener(this);
        tv_sure_pop.setOnClickListener(this);
        tv_quit_pop.setOnClickListener(this);


    }

    @Override
    protected void initData() {
        InputFilter[] emojiFilters = {emojiFilter};
        editText_ask.setFilters(new InputFilter[]{emojiFilter});
        editText_ask.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
              //  temp = s;
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                String edit = editText_ask.getText().toString();
                if (edit.length()>=0){
//                    toastMsg("问题描述未满10个字\n请重新输入");
                    int num = 500-edit.length();
                    if (num>=0){
                        tv_nums.setText(num+"");
                    }
                }else {
                    tv_nums.setText("最少输入10个字/500");
                }
            }
        });


        recyclerView_image.setLayoutManager(new GridLayoutManager(mContext, 3));

        if (dischargeSummaryBean != null) {
            images.addAll(dischargeSummaryBean.getImagePaths());
            for (int i = 0; i < dischargeSummaryBean.getImages().size(); i++) {
                ImageBean imageBean = new ImageBean();
                imageBean.setImage(dischargeSummaryBean.getImages().get(i));
                imageBean.setImageType(2);
                imageBeanList.add(imageBean);
            }
            if (dischargeSummaryBean.getImages().size() < 6) {
                ImageBean imageBean = new ImageBean();
                imageBean.setImageType(0);
                imageBeanList.add(imageBean);
            }
//            dischargeTime = dischargeSummaryBean.getDischargeTime() + "";
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String date = sdf.format(new Date(dischargeSummaryBean.getDischargeTime()));
//            tv_time.setText(date);
//            tv_content.setText(dischargeSummaryBean.getSummary());
        } else {
            for (int i = 0; i < 1; i++) {
                ImageBean imageBean = new ImageBean();
                imageBean.setImageType(0);
                imageBeanList.add(imageBean);
            }
        }



        imageAdapter = new ImageAdapter(imageBeanList,mContext);
        imageAdapter.setOnItemClickListener(this);
        recyclerView_image.setAdapter(imageAdapter);



        initOpp();


    }

    InputFilter emojiFilter = new InputFilter() {
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                toastMsg("不支持表情输入");
                return "";
            }
            return null;
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_title_back:
                Utils.hideSoftInputFromWindow(this, editText_ask);
                //closeInputMethodManager();
                if (!TextUtils.isEmpty(editText_ask.getText().toString())||images.size()>0){
                    popup_easynotice1.showAtLocation(tv_title, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                }else {
                    finish();
                }
                break;
            case R.id.ask_consult_ask:
                    if (editText_ask.getText().length()>=10){
                        askQuestPop.showAtLocation(ll_root_askQuestion, Gravity.CENTER,0,0);
                    }else {
                        toastMsg("问题描述未满10个字\n请重新输入");
                    }

                break;
            case R.id.askquestion_quit:
                askQuestPop.dismiss();
                break;
            case R.id.askquestion_sure:
                //数据上传服务器,在返回数据处退出跳转
                askQuestPop.dismiss();
                YiJiaHuNetWorkUtils.EditUpUserAndDoctor(loginInfo.getUserId(),editText_ask.getText().toString(),images,handler);
                break;
            case R.id.tv_cancle:
                popup_easynotice1.dismiss();
                break;
            case R.id.tv_sure:
                popup_easynotice1.dismiss();
                finish();
                break;

        }
    }
    public void initOpp() {
        if (popup_easynotice1 == null) {
            //easynotice
            popup_easynotice1 = new PopupWindow(this);
            final View viewNotice = LayoutInflater.from(this).inflate(R.layout.pop_sure_item, null);
            popup_easynotice1.setContentView(viewNotice);

            popup_easynotice1.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            popup_easynotice1.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            popup_easynotice1.setFocusable(true);
            popup_easynotice1.setTouchable(true);
            popup_easynotice1.setOutsideTouchable(true);
            popup_easynotice1.setBackgroundDrawable(new ColorDrawable(0x22000000));
            popup_easynotice1.setAnimationStyle(R.style.popupwindow_anim_alpha);
            tv_cancle = (TextView) viewNotice.findViewById(R.id.tv_cancle);
            tv_sure = (TextView) viewNotice.findViewById(R.id.tv_sure);
            tv_sure.setOnClickListener(this);
            tv_cancle.setOnClickListener(this);

            // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
            viewNotice.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    LinearLayout line_content = (LinearLayout) viewNotice.findViewById(R.id.line_content);
                    int height = line_content.getTop();
                    int bottom = line_content.getBottom();
                    int y = (int) event.getY();
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        if (y < height || bottom < y) {
                            //Log.d("xxxx", "xxxxx");
                            popup_easynotice1.dismiss();
                            //return false;
                        }
                    }

                    return true;
                }
            });
        }
    }
    @Override
    public void onItemClick(View view, int position) {
/**
 * 0表示是添加按钮,1表示读取本地图片,2表示网络
 */
        if (imageBeanList.get(position).getImageType() == 0) {
            Utils.hideSoftInputFromWindow(AskQuestionActivity.this, editText_ask);
            picSelect.setType(1);
            picSelect.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
            clickPosition = 0;
        } else {
            clickPosition = position;
            Intent intent = new Intent(mContext, DisplayImageActivity.class);
            intent.putExtra("path", imageAdapter.getImageBeen(position).getImage());
            if (imageBeanList.size() == 9 && imageBeanList.get(8).getImageType() != 0) {
                intent.putExtra("title", (position + 1) + "/" + imageBeanList.size());
                List<String>  picList=new ArrayList<>();
                for (int i = 0; i < imageBeanList.size(); i++) {
                    picList.add(imageBeanList.get(i).getImage());
                }
                intent.putStringArrayListExtra("pics", (ArrayList<String>) picList);
            } else {
                intent.putExtra("title", (position + 1) + "/" + (imageBeanList.size() - 1));
                List<String>  picList=new ArrayList<>();
                for (int i = 0; i < imageBeanList.size()-1; i++) {
                    picList.add(imageBeanList.get(i).getImage());
                }
                intent.putStringArrayListExtra("pics", (ArrayList<String>) picList);
            }
            intent.putExtra("position", position);

            //intent.putExtra("isHideDelete", "true");
            startActivityForResult(intent, DELETE_CODE);
        }
    }

    @Override
    public void onFinished(int options, int type) {
        cameraPath = new File(ApplicationConfig.PicAndVideoUrl);
        if (!cameraPath.exists()) {
            cameraPath.mkdirs();
        }
        Intent mIntent;
        if (options == 1) {// 打开相机
            if (type == 1) {// 拍照
                mIntent = new Intent();
                mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraFileName = System.currentTimeMillis() + ".jpg";
                cameraFile = new File(cameraPath, cameraFileName);
                mIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(cameraFile));
                startActivityForResult(mIntent,
                        TAKE_PHOTO_PICTURE);
            }
        } else if (options == 2) {// 打开相册
            if (type == 1) {

                // 相册选择照片
//                cameraFileName = System.currentTimeMillis() + ".jpg";
//                cameraFile = new File(cameraPath, cameraFileName);
//                Intent intent = null;
//                if (Build.VERSION.SDK_INT < 19) {
//                    intent = new Intent(Intent.ACTION_GET_CONTENT, null);
//                    intent.setType("image/*");
//                } else {
//                    intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                            "image/*");
//                }
//            /*    mIntent = new Intent(
//                        Intent.ACTION_PICK,
//                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                mIntent.setDataAndType(
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image*//*");*/
//                startActivityForResult(intent,
//                        SELECT_PICTURE);

                Intent intent = new Intent(this, MeenoPhotoActivity.class);
                intent.putExtra("maxNumber", (10-imageBeanList.size()));
                startActivityForResult(intent, PHOTO_MANY);

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case DELETE_CODE://删除
                    clickPosition = data.getIntExtra("position", -1);
                    if (clickPosition == -1)
                        return;
                    images.remove(clickPosition);
                    imageBeanList.remove(clickPosition);
                    if (images.size() == 8) {
                        ImageBean imageBean = new ImageBean();
                        imageBean.setImageType(0);
                        imageBeanList.add(imageBean);
                    }
                    imageAdapter.notifyDataSetChanged();
                    break;
                case TAKE_PHOTO_PICTURE:// 照相
                    if (resultCode == Activity.RESULT_OK) {
                        if (cameraFile != null) {
                            upImage(cameraFile);
                        }
                    }
                    break;
                case SELECT_PICTURE:// 选择照片
                    if (resultCode == Activity.RESULT_OK) {
                        if (data.getData() != null) {
                            Uri uri = data.getData();
                            if (uri != null) {
                                //创建图片保存目录
                                String path= UriUtils.getPath(AskQuestionActivity.this,uri);
                                final File file=new File(path);
                                if (file.exists()){
                                    upImage(file);

                                }
                      /*          cameraFileName = System.currentTimeMillis() + ".jpg";
                                cameraFile = new File(cameraPath, cameraFileName);
                                imageUri = Uri.fromFile(cameraFile);
                                Intent intent = new Intent("com.android.camera.action.CROP");
                                intent.setDataAndType(uri, "image*//*");
                                // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
                                intent.putExtra("crop", "true");
                                // aspectX aspectY 是宽高的比例
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                // outputX outputY 是裁剪图片宽高
//							intent.putExtra("outputX", 150);
//							intent.putExtra("outputY", 150);
                                intent.putExtra("return-data", false);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//文件输出路径
                                intent.putExtra("outputFormat", "JPEG"); //输入文件格式
                                startActivityForResult(intent, CUT_PICTURE);*/

                            }
                        }
                    }
                    break;
                case PHOTO_MANY:
                    if (resultCode == Activity.RESULT_OK)
                    {
                        if (data != null)
                        {
                            ArrayList<String> pics = data.getStringArrayListExtra("pics");

                            final JSONArray jsonArray = MyImageCompresseUtils.processPics(pics);
                            if(jsonArray.length() == 0)
                            {
                                return;
                            }

                            new Thread(new Runnable() {
                                @Override
                                public void run() {

                                    List<File> images = new ArrayList<>();
                                    for (int i = 0; i < jsonArray.length() ; i++)
                                    {
                                        try
                                        {
                                            File file = new File(jsonArray.getJSONObject(i).getString("url"));
                                            images.add(file);
                                        } catch (JSONException e)
                                        {
                                            e.printStackTrace();
                                        }
                                    }

                                    YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
                                }
                            }).start();
                            loading();

                            return;
                        }
                    }

                    break;
                case CUT_PICTURE://图片裁剪
                    if (imageUri != null) {
                        if (cameraFile != null) {
                            ImageVideoUtils.compressPicture(cameraFile, cameraFile);
                            // System.out.println("cameraFile.getAbsolutePath()====" + cameraFile.getAbsolutePath());
                            //mBitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
                            List<File> images = new ArrayList<>();
                            images.add(cameraFile);
                            YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
                            loading();
                        }
                    }
                    imageUri = null;
                    break;
            }
        }
    }
    private void upImage(final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ImageVideoUtils.compressThumbnail(file, cameraFile);
                List<File> images = new ArrayList<>();
                images.add(cameraFile);
                YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
            }
        }).start();
        loading();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK){
            Utils.hideSoftInputFromWindow(this, editText_ask);
            if (!TextUtils.isEmpty(editText_ask.getText().toString())||images.size()>0){
                popup_easynotice1.showAtLocation(tv_title, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
